<script type="text/javascript">
function remappingBean(){
	
	var bornDP =$("#born-datepicker").datepicker({
      	autoclose:"true", 
		format:"dd/mm/yyyy"
	});
		bornDP.on('changeDate', function(e){
		var date = $(this).datepicker('getDate');
		
		var dateVal = $.datepicker.formatDate('dd/mm/yy', date);
			$('#born').val(dateVal);
			$('#born').change();
		});
	
	 $('#born_province').select2({
         allowClear: true,
         minimumInputLength: 1,
         formatNoMatches:'Nessuna corripondenza',
         formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
         formatSearching:'Stiamo cercando le province...' ,
         ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
             url: "/province/list",
             dataType: 'json',
             quietMillis: 250,
             data: function (term, page) {
                 return {
                     index: term, // search term
                 };
             },
             results: function (data, page) { // parse the results into the format expected by Select2.
                 // since we are using custom formatting functions we do not need to alter the remote JSON data
                 return { results: data.results };
             },            
             cache: true
         },  
	 }); 
	 
	 $('#born_province').on("change", function(e) {
         ${remoteFunction(asynchronous: true,
	            				action:'get_municipality',
								controller:'province',
								params:'\'pr=\' + this.value',
								update:'born_municipality',
								onSuccess:'reset_born_municipality();reset_born_cap()'															
								)}   
	 });

     $('#born_municipality').select2({
     	allowClear: false,
         formatNoMatches:'Nessuna corripondenza',
         formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
         formatSearching:'Stiamo cercando i comuni...' ,
      });

     $('#born_municipality').on("change", function(e) {
         ${remoteFunction(asynchronous: true,
 				action:'get_cap',
					controller:'province',
					params:'\'mun=\' + this.value',
					onSuccess:'$("#born_cap").val(data)',
					)}        
	  });
		     
     function reset_born_municipality(){
			$("#born_municipality").select2("val","");
	 }

     function reset_born_cap(){
			$("#born_cap").val("");
	 }
			 
	 $('#fiscal_province').select2({
         allowClear: true,
         minimumInputLength: 1,
         formatNoMatches:'Nessuna corripondenza',
         formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
         formatSearching:'Stiamo cercando le province...' ,
         ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
             url: "/province/list",
             dataType: 'json',
             quietMillis: 250,
             data: function (term, page) {
                 return {
                     index: term, // search term
                 };
             },
             results: function (data, page) { // parse the results into the format expected by Select2.
                 // since we are using custom formatting functions we do not need to alter the remote JSON data
                 return { results: data.results };
             },
             
             cache: true
         },  
	 }); 
	 $('#fiscal_province').on("change", function(e) {
         ${remoteFunction(asynchronous: true,
	            				action:'get_municipality',
								controller:'province',
								params:'\'pr=\' + this.value',
								update:'fiscal_municipality',
								onSuccess:'reset_fiscal_municipality();reset_fiscal_cap()'															
								)}   
	 });
	 $('#fiscal_municipality').select2({
     	allowClear: false,
         formatNoMatches:'Nessuna corripondenza',
         formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
         formatSearching:'Stiamo cercando i comuni...' ,
      });

	 $('#fiscal_municipality').on("change", function(e) {
         ${remoteFunction(asynchronous: true,
 				action:'get_cap',
					controller:'province',
					params:'\'mun=\' + this.value',
					onSuccess:'$("#fiscal_cap").val(data)',
					)}        
		});
	 function reset_fiscal_municipality(){
			$("#fiscal_municipality").select2("val","");
		}
	 function reset_fiscal_cap(){
			$("#fiscal_cap").val("");
		}	
		
		$(".select2-hidden-accessible").addClass('text-uppercase');
       	$(':input').addClass('text-uppercase');
		$(':radio,:checkbox').addClass('text-uppercase');
		$('.select2-chosen').addClass('text-uppercase');
		$( ":button" ).addClass('text-uppercase');
		$('select').addClass('text-uppercase');
		
	 $.validator.addMethod('italiandate', function (value) {
	       return /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(value) || /^$/.test(value);;
	}, 'Inserire una data valida (gg/mm/aaaa)');		
		$.validator.addMethod('lettersspaceacc', function (value) {
		       return /^[a-zA-Zàèìòùé\'\s]*$/.test(value);
		}, 'Inserisci solo lettere o spazi');
		$.validator.addMethod('lettersspaceonly', function (value) {
		       return /^[a-zA-Z\s]*$/.test(value);
		}, 'Inserisci solo lettere o spazi');		
		$.validator.addMethod('numericOnly', function (value) {
		       return /^[0-9]+$/.test(value);
		}, 'Please only enter numeric values (0-9)');
		$.validator.addMethod('numericOnlyNull', function (value) {
		       return /^[0-9]+$/.test(value) || /^$/.test(value);
		}, 'Solo Valori numerici (0-9)');
		$.validator.addMethod('CF', function (value) {
		       return /^[a-z]{6}\d{2}[abcdehlmprst]\d{2}[a-z]\d{3}[a-z]/i.test(value) ;
		}, 'Inserire un codice fiscale valido');
		$.validator.addMethod('PIVA', function (value) {
		       return  /^[0-9]{11}$/.test(value) || /^$/.test(value);
		}, 'Inserire una partita iva valida');
		
		$.validator.addMethod("selectNotEquals", function(value, element, arg){
							  return arg != value;
							 }, "Bisogna Selezionare il responsabile");

		var $validator = $('#add_user_form').validate({
		    rules: {
		    	owner:{
		    		 selectNotEquals: "-1"	
		    	},
		    	
		      username:{
		      	required: true,
		        rangelength:[2,50],
		       <g:if test='${!user}'>
		        "remote":
                {
                  url: '${createLink(controller:'user',action:'check_unique')}',
                  type: "post",
                  data:
                  {
                      code: function()
                      {
                          return $('#username').val();
                      }
                  }
                }
		      </g:if>
		      },
		      password:{
				required: true,
				rangelength:[8,50],
		      },
		      name: {
		        required: true,
		        rangelength:[2,50],
		        lettersspaceacc:true,
		        
		      },
		      surname: {
		    	  required: true,
			        rangelength:[2,50],
			        lettersspaceacc:true,
		      },
		      cf:{
					 required: true,
					 CF:true,
					 },
			 piva:{
				 required: false,
				 PIVA:true,
				},
			phone: {
		        required: false,
		        minlength: 10,
		        numericOnlyNull:true
		      },
		      mobile:{
		    	  required: false,
			      },    	 
			 personal_email: {
			        required: false,
			        email: true
			      },
		      company_email: {
			        required: false,
			        email: true
			      },      
		      born:{
		    	  required: false,
		    	  italiandate:true
			      },
			    
		      age: {
		        required: false,
		        numericOnlyNull:true
		      }
		       
		    },
		    
		    messages: {
		      username:{
			      required:"Bisogna spedificare il codice dell'utente",
			      nowhitespace:"Non puoi inserire spazi",
			      rangelength:"Username deve essere almeno di {0} caratteri e al massimo di {1} caratteri",
                  remote: jQuery.validator.format("{0} è un codice già usato nella piattaforma.")
			      
			      }, 
			   password:{
			   	  required:"Bisogna spedificare la password dell'utente",
			      rangelength:"La password deve essere almeno di {0} caratteri "
			   },   
		      name:{
			      required:"Bisogna spedificare il nome dell'utente",
			      nowhitespace:"Non puoi inserire spazi",
			      rangelength:"Il nome deve essere almeno di {0} caratteri e al massimo di {1} caratteri",
			      lettersonly:"Non puoi inserire numeri nel nome"
			      }, 
		      surname:{
			      required:"Bisogna spedificare il cognome dell'utente",
			      nowhitespace:"Non puoi inserire spazi",
			      rangelength:"Il cognome deve essere almeno di {0} caratteri e al massimo di {1} caratteri",
			      lettersonly:"Non puoi inserire numeri nel cognome"
			      },
			   born:{
					  required:"Inserire la data di nascita dell'utente"
				},
			 cf:{
				  required:"Inserire il Codice Fiscale dell'utente"
				 },
			   age:{
				  required:"Inserire l'età dell'utente",
				  numericOnly:"Inserire solo numeri"
				  } ,
			 
				phone: {
			        required: "Inserire il telefono dell'utente",
			        minlength: "Il numero di telefono deve essere almeno di 10 numeri",
			        numericOnly:"Il numero di telefono deve contenere solo numeri"
			      },
			      mobile:{
			    	  required: "Inserire il cellulare dell'utente",
			      },
			 personal_email: {
		        required: "Devi inserire un email per l'utente",
		        email: "Inserire un formato email valido [name@domain.com]"
		      }
		    },
		    
		    highlight: function (element) {
		      $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
		    },
		    unhighlight: function (element) {
		      $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
		    },
		    errorElement: 'span',
		    errorClass: 'help-block',
		    errorPlacement: function (error, element) {
		      if (element.parent('.input-group').length) {
		        error.insertAfter(element.parent());
		      } else {
		        error.insertAfter(element);
		      }
		    },
		    invalidHandler: function(form, validator) {
				$("#validity_label").html('<i class="fa-fw fa fa-warning"></i>Ci sono '+validator.numberOfInvalids()+' infomazion'+(validator.numberOfInvalids()>1?'i':'e')+' mancant'+(validator.numberOfInvalids()>1?'i':'e'));
				$("#validity_label").show();
			}
		  });

	<g:if test="${user?.bornProvince}">
		console.log("{id:${user?.bornProvince.id},text:'${user?.bornProvince.nome}'}")
	 	$("#born_province").select2('data',{id:${user?.bornProvince.id},text:'${user?.bornProvince.nome}'});
	</g:if>
	<g:if test="${user?.bornMunicipality}">
		$("#born_municipality").append($('<option>', {value:"${user?.bornMunicipality?.id}", text: "${user?.bornMunicipality?.nome}"}));
		$("#born_municipality").select2("val","${user?.bornMunicipality?.id}");
	</g:if>
	<g:if test="${user?.fiscalAddress?.province}">
		 $("#fiscal_province").select2('data',{id:${user.fiscalAddress.province.id},text:'${user.fiscalAddress.province.nome}'});
	</g:if>
	<g:if test="${user?.fiscalAddress?.municipality}">
		$("#fiscal_municipality").append($('<option>', {value:"${user?.fiscalAddress?.municipality?.id}", text: "${user?.fiscalAddress?.municipality?.nome}"}));
		$("#fiscal_municipality").select2("val","${user?.fiscalAddress?.municipality?.id}");
	</g:if>
	
		}	

</script>

				<g:hasErrors bean="${user}">
				<div class="alert alert-danger fade in">
					<g:renderErrors bean="${user}" as="list" />
				</div>
				</g:hasErrors>
				<form action="save" id="add_user_form" method="POST">
					<g:if test="${user}">
					<input type="hidden" id="user_id" name="user_id" value="${user.id}">
					</g:if>	
					<g:if test="${role}">
					<div class="alert alert-info fade in">Inserimento nuovo ${role.label}</div>
					<input type="hidden" id="role_id" name="role_id" value="${role.id}">
					</g:if>	
					<g:if test="${owners}">
					<div class="row col-lg-10 ">
					<div class="form-group">
					<div class="input-group">
					
						<span class="input-group-addon"><i class="fa fa-group fa-lg fa-fw"></i></span>
						<g:select class="form-control" name="owner" from="${owners}"  optionKey="id" noSelection="['-1':'Selezionare il responsabile']" value="${owner_selected}"/>
					</div>
					</div>
					</div>
					</g:if>
				<div class="row col-lg-10 ">
				
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-user fa-lg fa-fw"></i></span>
						<input class="form-control input-md" placeholder="Codice ${role.label} *" type="text" name="username" id="username" value="${user?.username}" <g:if test="${user}">readonly="readonly"</g:if>>
		
					</div>
				</div>
				
				</div>
				<g:if test="${!user?.password}">
				<div class="row col-lg-10 ">
				
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></span>
						<input class="form-control input-md" placeholder="Password *" type="password" name="password" id="password" >
					</div>
				</div>
				</div>
				</g:if>
				
				
				<div class="row col-lg-10 ">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-info fa-lg fa-fw"></i></span>
						<input class="form-control input-md" placeholder="Nome *" type="text" name="name" id="name" value="${user?.name}">
					</div>
				</div>
			</div>
			<div class="row col-lg-10 ">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-info fa-lg fa-fw"></i></span>
						<input class="form-control input-md" placeholder="Cognome / Rag. Sociale*" type="text" name="surname" id="surname" value="${user?.surname}">
					</div>
				</div>
			</div>
			<div class="row col-lg-10 ">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-info fa-lg fa-fw"></i></span>
						<input class="form-control input-md" placeholder="Codice Fiscale" type="text" name="cf" id="cf" value="${user?.cf}">
					</div>
				</div>
			</div>
			<div class="row col-lg-10 ">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-info fa-lg fa-fw"></i></span>
						<input class="form-control input-md" placeholder="Partita Iva" type="text" name="piva" id="piva" value="${user?.piva}">
					</div>
				</div>
			</div>
			<div class=" row col-lg-10">
				<div class="form-group">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-phone fa-lg fa-fw"></i></span>
												<input  style="width:100%" placeholder="Telefono" class="form-control input-md" name="phone" id="phone"  value="${user?.phone}"/>
			
						</div>
					</div>
			</div>
			<div class="row col-lg-10">
				<div class="form-group">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-mobile-phone fa-lg fa-fw"></i></span>
												<input data-mask="+39 999 9999999" data-mask-placeholder="X" style="width:100%" placeholder="Cellulare" class="form-control input-md" name="mobile" id="mobile" value="${user?.mobile}"/>
			
						</div>
					</div>
			</div>
			<div class="row col-lg-10">
				<div class="form-group">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-envelope fa-lg fa-fw"></i></span>
							<input class="form-control input-md" placeholder="Email Personale" type="email" name="personal_email" id="personal_email" value="${user?.personal_email}">
			
						</div>
					</div>
			</div>
			<div class="row col-lg-10">
				<div class="form-group">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-envelope fa-lg fa-fw"></i></span>
							<input class="form-control input-md" placeholder="Email Aziendale" type="email" name="company_email" id="company_email" value="${user?.company_email}">
						</div>
					</div>
			</div>
			<div class="row col-lg-10">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-map-marker fa-lg fa-fw" ></i></span>
						<input style="width:100%" data-placeholder="Provincia di nascita" class="input-md" name="bornProvince" id="born_province" />
		
					</div>
				</div>
			</div>
			<div class="row col-lg-10">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-map-marker fa-lg fa-fw"></i></span>
						<select style="width:100%" data-placeholder="Comune di nascita" class="input-md" name="born_municipality" id="born_municipality" >
							<option></option>
						</select>
					</div>
				</div>
			</div>
			<div class="row col-lg-10">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-map-marker fa-lg fa-fw"></i></span>
						<input class="form-control input-md" placeholder="CAP" type="text" name="born_cap" id="born_cap" 
								readonly="readonly" value="${user?.bornCap}">
					</div>
				</div>
			</div>			
			<div class="row col-lg-10 ">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa  fa-calendar fa-lg fa-fw" id="born-datepicker"></i></span>
						<input
                        	type="text" 
                        	placeholder="Data Nascita"
							name="born"
							id="born"
							value="${formatDate(format:'dd/MM/yyyy',date:user?.born)}" 
							class="form-control input-md"
							onchange="${remoteFunction(
								asynchronous: false,
	            				action:'calculate_age',
								controller:'interview',
								params:'\'born=\' + this.value',
								onSuccess: 'showAge(data,textStatus);'
								
								)}"
							
                        />
					</div>
				</div>
			</div>
			<div class="row col-lg-10 ">
				<div class="form-group">
					<div class="input-group">
						<span class="input-group-addon"><i class="fa fa-info fa-lg fa-fw"></i></span>
						<input class="form-control input-md" readonly placeholder="Et&agrave;" type="text" name="age" id="age" value="${user?.age}">
					</div>
				</div>
			</div>
			<div class="row col-lg-10 ">
			<div class="panel-group smart-accordion-default" id="accordion-2">
			<div class="panel panel-default">
				<div class="panel-heading">
					<h4 class="panel-title"><a data-toggle="collapse" data-parent="#accordion-2" href="#collapseOne-1" class="collapsed"> 
						<i class="fa fa-fw fa-plus-circle txt-color-green"></i> 
							<i class="fa fa-fw fa-minus-circle txt-color-red"></i>Residenza Fiscale</a></h4>
				</div>
				<g:if test="${user?.fiscalAddress}">
					<div id="collapseOne-1" class="panel-collapse collapse in">
				</g:if>
				<g:else>
					<div id="collapseOne-1" class="panel-collapse collapse">
				</g:else>
					<div class="panel-body" style="background: url(/site/img/mybg.png) #fff;">
						<div class="row">
							<div class="col-lg-10 ">
								<div class="form-group">
									<div class="input-group">
										<span class="input-group-addon"><i class="fa fa-map-marker fa-lg fa-fw"></i></span>
										<input style="width:100%" data-placeholder="Provincia" class="input-md" 
											name="fiscalAddress.province" id="fiscal_province" onblur=""
										/>
		
									</div>
								</div>
							</div>
							</div>
							<div class="row">
							<div class="col-lg-10 ">
								<div class="form-group">
									<div class="input-group" id="input-group-abode_municipality">
										<span class="input-group-addon"><i class="fa fa-map-marker fa-lg fa-fw"></i></span>
											<select style="width:100%" data-placeholder="Comune" class="input-md" name="fiscalAddress.municipality" id="fiscal_municipality" >
												<option></option>									
											</select>									
									</div>
								</div>
							</div>
						</div>

						<div class="row">
						
							<div class="col-lg-10 ">
							<div class="form-group">
									<div class="input-group">
										<span class="input-group-addon"><i class="fa fa-map-marker fa-lg fa-fw"></i></span>
															<input class="form-control input-md" placeholder="CAP" type="text" name="fiscalAddress.cap" id="fiscal_cap" readonly="readonly" value="${user?.fiscalAddress?.cap}">
						
									</div>
								</div>
						</div>
						</div>
						<div class="row">
						<div class="col-lg-10">
							<div class="form-group">
									<div class="input-group">
										<span class="input-group-addon"><i class="fa fa-map-marker fa-lg fa-fw"></i></span>
															<input style="width:100%" placeholder="Indirizzo" class="form-control input-md" name="fiscalAddress.address" id="fiscal_address" value="${user?.fiscalAddress?.address}"/>
						
									</div>
								</div>
						</div>
						</div>
								</div>
						</div>
			</div>
			<br/>
			<br/>
			</div>
			<div class="row ">
			<div class="col-lg-5">
			<div class="smart-form inline-group">
				<label class="radio">
					<input type="radio" name="enabled" class="checkbox_sex" value="1" <g:if test="${user?.enabled || (!user)}">checked</g:if>>
					<i></i>Attivo</label>	
			</div>
		</div>
		<div class="col-lg-5">
			<div class="smart-form inline-group">
				<label class="radio">
					<input type="radio" name="enabled" class="checkbox_sex" value="0" <g:if test="${user && !(user?.enabled)}">checked</g:if>>
					<i></i>Disattivo</label>
			</div>
		</div>
		</div>
		<div class="row "><br/><br/></div>
			<div class="row ">
			<div class="col-lg-4 ">
				
				<div class="form-group">
					<div class="input-group">
						<g:if test="${user}">
						<g:set var="btn_value" value="Aggiorna"></g:set>
						</g:if><g:else>
						<g:set var="btn_value" value="Salva"></g:set>
						</g:else>
						<g:submitToRemote class="btn btn-primary btn-lg" url="[action: 'save']" update="manage_users_section"  before="validateAddUser()" value="${btn_value}"></g:submitToRemote>
						
						
					</div>
				</div>
				</div>
				<div class="col-lg-4 ">
				
				<div class="form-group">
					<div class="input-group">
					<a href="${createLink(action:'show') }" class="btn btn-default btn-lg" >Annulla</a>
					</div>
				</div>
				</div>
				
			</div>
</form>
